import datetime

from django.shortcuts import redirect
from django.utils.deprecation import MiddlewareMixin
from django.conf import settings
from web import models
class Tracer(object):
    def __init__(self):
        self.user = None
        self.price_policy = None
        self.project = None

class AuthMiddleware(MiddlewareMixin):
    def process_request(self,request):
        """如果用户已登录，则request中传入用户对象"""
        request.tracer = Tracer()
        user_id = request.session.get('user_id', 0)
        user_object = models.UserInfo.objects.filter(id=user_id).first()
        request.tracer.user = user_object
        """
        1.获取当前页面访问的url
        2.检查是否白名单
        """
        if request.path_info in settings.WHITE_REGEX_URL_LIST:
            return
        # # 检查用户是否已登录,未登录则返回登录页面
        if not request.tracer.user:
            return redirect('login')
        """
        # 获取当前用户所拥有的的额度
        # 方式一、免费额度在交易记录中存储
        """
        #获取已支付的用户，当前用户ID值最大
        _object = models.Transaction.objects.filter(user=user_object,status=2).order_by('-id').first()
        #判断 付费用户 且 过期
        curent_datetime = datetime.datetime.now()
        if _object.end_datetime and _object.end_datetime < curent_datetime:
            _object = models.Transaction.objects.filter(user=user_object, status=2,price_policy_category=1).first()
        request.tracer.price_policy = _object.price_policy
        """
        # 获取当前用户所拥有的的额度
        # 方式二、免费的额度存在配置文件
        """
        # # 获取已支付的用户，当前用户ID值最大
        # _object = models.Transaction.objects.filter(user=user_object, status=2).order_by('-id').first()
        # if not _object:
        #     #没有购买
        #     request.tracer.price_policy = models.PricePolicy.objects.filter(category=1, title="个人免费版").first()
        # else:
        #     request.tracer.price_policy = _object.price_policy

    def process_view(self,request,view,args,kwargs):
        #判断url是否以manage开头
        if not request.path_info.startswith('/manage/'):
            return
        #判断是否我创建的项目
        project_id = kwargs.get('project_id')
        project_object = models.Project.objects.filter(creator=request.tracer.user,id= project_id).first()
        if project_object:
            request.tracer.project = project_object
            return
        #判断是否我参与的项目
        project_user_object = models.ProjectUser.objects.filter(user=request.tracer.user,project_id=project_id).first()
        if project_user_object:
            request.tracer.project = project_user_object.project
            return
        #如果不是我创建的 参与的 项目，则返回项目列表页面
        return redirect('project_list')



